package controller;

import dao.UserDAOImpl;
import model.TUser;
import utils.DispatcherUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", value = "/register.do")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userid = request.getParameter("userid");
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        String phone = request.getParameter("phone");
        String utid = request.getParameter("utid");

        if(userid==null||userid.equals("")){
            DispatcherUtils.openErrWeb("用户ID不能为空","register.jsp",request,response);
            return;
        }

        if(username.equals("")||username==null){
            DispatcherUtils.openErrWeb("用户名不能为空","register.jsp",request,response);
            return;
        }

        if(pwd.equals("")||pwd==null){
            DispatcherUtils.openErrWeb("登录密码不能为空","register.jsp",request,response);
            return;
        }

        if(phone.equals("")||phone==null){
            DispatcherUtils.openErrWeb("联系方式不能为空","register.jsp",request,response);
            return;
        }

        UserDAOImpl userDAO = new UserDAOImpl();
        TUser tUser = new TUser();

        tUser.setUtid(Integer.parseInt(utid));
        tUser.setUserid(userid);
        tUser.setPhone(phone);
        tUser.setUsername(username);
        tUser.setPwd(pwd);

        if(userDAO.addUser(tUser)){
            response.sendRedirect("login.jsp");
        }else{
            DispatcherUtils.openErrWeb("数据库服务器出现问题，或者注册信息长度过长","register.jsp",request,response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
